<template>
  <div class="user-page">
    <!-- 用户信息卡片 -->
    <div class="user-card">
      <div class="user-avatar">
        <van-image
          :src="userInfo.avatar"
          round
          width="60"
          height="60"
          fit="cover"
        />
      </div>
      <div class="user-info">
        <h3 class="username">{{ userInfo.nickname || '未登录' }}</h3>
        <p class="user-desc">{{ userInfo.description || '仅支持在校学生教师登录' }}</p>
      </div>
      <div class="user-action">
        <van-button plain
          v-if="!userInfo.isLoggedIn"
          type="danger"
          size="small"
          round
          @click="goToLogin"
        >
          登录
        </van-button>
        <van-button
          v-else
          type="warning"
          size="small"
          round
          @click="handleLogout"
        >
          退出
        </van-button>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="menu-section">
      <van-cell-group>
        <van-cell
          title="我的收藏"
          icon="star-o"
          is-link
          :badge="favoriteCount"
          @click="goToFavorites"
        />
        <van-cell
          title="浏览历史"
          icon="clock-o"
          is-link
          :badge="historyCount"
          @click="goToHistory"
        />
        <van-cell
          title="消息通知"
          icon="bell"
          is-link
          :badge="notificationCount"
          @click="goToNotifications"
        />
      </van-cell-group>
    </div>

    <!-- 设置菜单 -->
    <div class="menu-section">
      <van-cell-group>
        <van-cell
          title="设置"
          icon="setting-o"
          is-link
          @click="goToSettings"
        />
        <van-cell
          title="关于我们"
          icon="info-o"
          is-link
          @click="goToAbout"
        />
        <van-cell
          title="意见反馈"
          icon="comment-o"
          is-link
          @click="goToFeedback"
        />
      </van-cell-group>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showToast, showSuccessToast } from 'vant'
import { userApi } from '../utils/api'
import { useUserStore } from '../stores/user'
import { useFavoritesStore } from '../stores/index.js'
import { useHistoryStore } from '../stores/history'

const router = useRouter()
const userStore = useUserStore()
const favoritesStore = useFavoritesStore()
const historyStore = useHistoryStore()

// 响应式数据
const { userInfo } = storeToRefs(userStore)
const { favoriteCount } = storeToRefs(favoritesStore)
const { historyCount } = storeToRefs(historyStore)
const notificationCount = ref(2) // 模拟数据，显示2条未读通知
// TODO: 待后端提供真实数据后替换
// 实际应从接口获取通知数量
// API路径: /api/notifications/count
// 请求方法: GET
// 返回示例: { count: 5 }

// 跳转到收藏页面
const goToFavorites = () => {
  // 收藏功能不需要登录，直接跳转
  router.push({ name: 'favorites' })
}

// 跳转到历史记录
const goToHistory = () => {
  router.push({ name: 'history' })
}

// 跳转到通知页面
const goToNotifications = () => {
  if (!userInfo.value.isLoggedIn) {
    showToast('请先登录')
    return
  }
  router.push({ name: 'notifications' })
}

// 跳转到设置页面
const goToSettings = () => {
  router.push({ name: 'settings' })
}

// 跳转到关于我们
const goToAbout = () => {
  router.push({ name: 'about' })
}

// 跳转到意见反馈
const goToFeedback = () => {
  router.push({ 
    name: 'feedback',
    // TODO: 待后端提供真实数据后替换
    // 当前为模拟数据，实际应从接口获取用户信息
    // query: {
    //   userId: userInfo.value.id,
    //   username: userInfo.value.nickname
    // }
  })
}

// 跳转到登录页面
const goToLogin = () => {
  router.push({ name: 'login' })
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await showConfirmDialog({
      title: '确认退出',
      message: '确定要退出登录吗？',
      theme:'round-button',
      confirmButtonText: '退出',
      confirmButtonColor: '#ee0a24'
    })

    // 使用Pinia store处理登出
    await userStore.logout(userApi.logout)

    // 清除记住的用户名
    localStorage.removeItem('rememberedUser')

    notificationCount.value = 0

    showSuccessToast('已退出登录')
  } catch (error) {
    // 用户取消退出
  }
}

// 验证用户登录状态
const verifyLoginStatus = async () => {
  try {
    // 使用userStore的checkLoginStatus方法验证登录状态
    const isLoggedIn = await userStore.checkLoginStatus(userApi.getPermission)

    // 更新通知数量
    if (isLoggedIn && userInfo.value.isLoggedIn) {
      notificationCount.value = 2
    } else {
      notificationCount.value = 0
    }

    console.log('用户登录状态验证完成:', isLoggedIn)
  } catch (error) {
    console.error('验证登录状态失败:', error)
    notificationCount.value = 0
  }
}

// 页面加载时获取用户信息
onMounted(async () => {
  // 初始化用户信息（Pinia store会自动初始化）
  // userStore.initUserInfo() // 已在store中自动初始化

  // 初始化收藏数据（Pinia store会自动初始化）
  // favoritesStore.initFavorites() // 已在store中自动初始化

  // 验证用户登录状态并更新UI
  await verifyLoginStatus()
})
</script>

<style scoped>
.user-page {
  padding-bottom: 60px; /* TabBar高度 */
  min-height: 100vh;
  background-color: #f7f8fa;
}

.user-card {
  display: flex;
  align-items: center;
  padding: 20px 16px;
  background: white;
  margin-bottom: 8px;
  cursor: pointer;
}

.user-avatar {
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: 600;
  color: #323233;
  margin: 0 0 4px 0;
}

.user-desc {
  font-size: 14px;
  color: #969799;
  margin: 0;
}

.arrow-icon {
  color: #c8c9cc;
}

.menu-section {
  margin-bottom: 8px;
}

.action-section {
  padding: 16px;
}

/* 自定义Cell样式 */
:deep(.van-cell) {
  padding: 16px;
}

:deep(.van-cell__title) {
  font-size: 16px;
}

:deep(.van-cell__left-icon) {
  margin-right: 12px;
  font-size: 18px;
}
</style>
